//src/stores/user.js
import { defineStore } from 'pinia';
import { jwtDecode } from 'jwt-decode';
import notify from '@/api/notify';
import user from '@/api/user';

export const userStore = defineStore('userStore', {
    state: () => ({
        userId: null,
        departmentId: null,
        departmentName: null,
        account: null,
        name: null,
        identity: null,
        sex: null,
        password: "*********",
        phone: null,
        email: null,
        authenticationFlag: null,
        directorFlag: null,
        userRole: null,
    }),
    actions: {
        // 解密 token 并填充用户信息
        async updateMyInfo() {
            const res = await user.getUserInfo();
            if (res.success) {
                localStorage.setItem('token', res.data);
                this.clearUserInfo()
                this.decodeToken();
                notify.success('信息更新成功');
            }else {
                notify.error('信息更新失败');
            }
        },
        decodeToken() {
            const token = localStorage.getItem('token'); // 从 localStorage 获取 token
            if (token) {
                try {
                    const decodedToken = jwtDecode(token); // 使用 jwt-decode 解码 token
                    const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
                    // 检查 token 是否过期
                    if (decodedToken.exp && decodedToken.exp < currentTime) {
                        throw new Error('Token expired');
                    }
                    const decoded = jwtDecode(token); // 解码 token
                    this.userId = decoded.userId;
                    this.departmentId = decoded.departmentId;
                    this.departmentName = decoded.departmentName;
                    this.account = decoded.account;
                    this.name = decoded.name;
                    this.identity = decoded.identity;
                    this.sex = decoded.sex;
                    this.phone = decoded.phone;
                    this.email = decoded.email;
                    this.authenticationFlag = decoded.authenticationFlag;
                    this.directorFlag = decoded.directorFlag;
                    this.userRole = decoded.userRole;
                } catch (error) {
                    localStorage.removeItem('token');
                    notify.error('信息已过期，请重新登录');
                }
            }
        },
        //清除用户信息
        clearUserInfo() {
            this.userId = null;
            this.departmentId = null;
            this.departmentName = null;
            this.account = null;
            this.name = null;
            this.identity = null;
            this.sex = null;
            this.password = "*********";
            this.phone = null;
            this.email = null;
            this.authenticationFlag = null;
            this.directorFlag = null;
            this.userRole = null;
        }
    }
});
